<template>
    <div class="l-from-body" >
        <el-form :model="formData" size="mini" :rules="rules"  ref="form" label-width="88px"  >
            <el-col :span="24">
                <el-form-item :label="$t('功能')" prop="f_Code">
                    <l-tree-select 
                        v-model="formData.f_Code"
                        :options="myModules"
                        @change="handleModuleChange"
                        ></l-tree-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item :label="$t('名称')" prop="f_Name">
                    <el-input v-model="formData.f_Name"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item :label="$t('对象类型')" prop="f_ObjectType">
                    <l-radio v-model="formData.f_ObjectType" :options="[{value:1,label:'角色'},{value:2,label:'用户'}]" ></l-radio>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item :label="$t('授权对象')" prop="f_ObjectId">
                    <l-select v-if="formData.f_ObjectType == 1" v-model="formData.f_ObjectId" :options="lr_roleOptions(lr_roles)" ></l-select>
                    <l-user-select v-else v-model="formData.f_ObjectId"></l-user-select>
                </el-form-item>
            </el-col>
            <el-col :span="24" style="padding-left:34px;">
                <draggable
                    :list="conditions"
                    :group="{ name: 'dic' }"
                    ghost-class="set-item-ghost"
                    handle=".l-drag-item">
                    <div v-for="(item, index) in conditions"
                        class="l-set-item l-set-item__Num" 
                        :key="index">
                        <i class="l-drag-item el-icon-rank"></i>
                        <el-tag type="info" size="medium" effect="plain">{{index + 1}}</el-tag>
                        <l-select
                            style="width:26%;margin-right:1%;"
                            size="mini"
                            v-model="item.f_FieldId"
                            :options="columns"
                            placeholder="字段"
                            :clearable="false"
                            
                            @change="handleChangeField"
                            ></l-select>
                        <l-select style="width:14%;margin-right:1%;"
                            size="mini"
                            v-model="item.f_Symbol"
                            :placeholder="$t('比较符')"
                            :options="symbolOptions"
                            :clearable="false"
                            >
                        </l-select>
                        <l-select style="width:21%;margin-right:1%;"
                            size="mini"
                            v-model="item.f_FiledValueType"
                            :placeholder="$t('字段值类型')"
                            :options="vTypeOptions"
                            :clearable="false"
                            @change="handleChangeVType(item)"
                            >
                        </l-select>
                        <el-input
                            :readonly="item.f_FiledValueType != 1 && item.f_FiledValueType != 10 "
                            style="width:25%;margin-right:1%;"
                            size="mini"
                            v-model="item.f_FiledValue"
                            :placeholder="$t('字段值')"></el-input>
                        <l-select style="width:10%;"
                            size="mini"
                            v-model="item.group"
                            :placeholder="$t('分组')"
                            :options="groupOptions"
                            :clearable="false"
                            @change="handleChangeGroup(item)"
                            >
                        </l-select>
                        <el-button 
                            @click="handleRemoveConditions(index)"
                            circle
                            plain
                            type="danger"
                            size="mini"
                            icon="el-icon-minus"
                            class="l-delete-item"
                            style="padding: 4px;"></el-button>
                    </div>
                </draggable>
                <div style="padding-left:22px;" >
                    <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="handleAddConditions"  >添加过滤条件</el-button>
                </div>
            </el-col> 
            <el-col :span="24" style="padding-left:34px;">
                <draggable
                    :list="formulas"
                    :group="{ name: 'dic' }"
                    ghost-class="set-item-ghost"
                    handle=".l-drag-item">
                    <div v-for="(item, index) in formulas"
                        class="l-set-item l-set-item__Num" 
                        :key="index">
                        <i class="l-drag-item el-icon-rank"></i>
                        <el-tag type="info" size="medium" effect="plain">{{numIndex[index]}}</el-tag>
                        <el-input
                            style="width:100%;"
                            size="mini"
                            v-model="item.value"
                            :placeholder="$t('please enter分组公式')">
                                <el-popover
                                    slot="append"
                                    placement="bottom"
                                    width="240"
                                    trigger="hover">

                                    <div class="l-info-message">
                                        <p>{{ $t('请按如下规则Edit条件组合') }}</p>
                                        <p class="ok">(1 and 2) or (3 and 4) <i class="fa fa-check"></i></p>
                                        <p>{{ $t('1.有and和or必须加括号') }}</p>
                                        <p class="error">1 and 2 or 3 and 4 <i class="fa fa-close"></i></p>
                                        <p>{{ $t('2.一个括号里不能同时出现and和or') }}</p>
                                        <p class="error">(1 and 2 or 3 )and 4 <i class="fa fa-close"></i></p>
                                        <p>{{ $t('3.不允许出现不存在的编号') }}</p>
                                        <p class="error">1 and 2 and 3 and 4 and 5 <i class="fa fa-close"></i></p>
                                        <p>{{ $t('4.括号都是成对出现的') }}</p>
                                        <p class="error">(1 and 2 and 3 and 4 <i class="fa fa-close"></i></p>
                                    </div>    
                                    <el-button  slot="reference" icon="el-icon-question"></el-button>
                                </el-popover>
                            </el-input>
                        <el-button 
                            @click="handleRemoveFormulas(index)"
                            circle
                            plain
                            type="danger"
                            size="mini"
                            icon="el-icon-minus"
                            class="l-delete-item"
                            style="padding: 4px;"></el-button>
                    </div>
                </draggable>
                <div style="padding-left:22px;" >
                    <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="handleAddFormulas"  >{{ $t('添加分组公式') }}</el-button>
                </div>
            </el-col> 
            <el-col :span="24">
                <el-form-item label="公式" prop="f_Formula">
                    <el-input v-model="formData.f_Formula" :placeholder="$t('please enter公式,默认为 1 and 2 and 3 and A and B 这种且方式')">
                        <el-popover
                            slot="append"
                            placement="bottom"
                            width="240"
                            trigger="hover">

                            <div class="l-info-message">
                                <p>{{ $t('请按如下规则Edit条件组合') }}</p>
                                <p class="ok">(1 and 2) or (3 and 4) <i class="fa fa-check"></i></p>
                                <p>{{ $t('1.有and和or必须加括号') }}</p>
                                <p class="error">1 and 2 or 3 and 4 <i class="fa fa-close"></i></p>
                                <p>{{ $t('2.一个括号里不能同时出现and和or') }}</p>
                                <p class="error">(1 and 2 or 3 )and 4 <i class="fa fa-close"></i></p>
                                <p>{{ $t('3.不允许出现不存在的编号') }}</p>
                                <p class="error">1 and 2 and 3 and 4 and 5 <i class="fa fa-close"></i></p>
                                <p>{{ $t('4.括号都是成对出现的') }}</p>
                                <p class="error">(1 and 2 and 3 and 4 <i class="fa fa-close"></i></p>
                            </div>    
                            <el-button  slot="reference" icon="el-icon-question"></el-button>
                        </el-popover>
                    </el-input>
                </el-form-item>
            </el-col>
        </el-form>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
const api = window.$api.custmerForm.module
const apiScheme = window.$api.custmerForm.scheme
const apiApp = window.$api.mapp.module

export default {
    data(){
        return {
            formData:{
                f_Code: '',
                f_Name: '',
                f_Formula: '',
                f_Type:2,

                f_ObjectType:1,
                f_ObjectId:''
            },
            rules: {
                f_Code: [
                    { required: true, message: this.$t('please select功能') },
                ],
                f_Name: [
                    { required: true, message: this.$t('please enter名称') }
                ],
                f_ObjectId: [
                    { required: true, message: this.$t('please select授权对象') }
                ],
            },

            symbolOptions:[
                { value: 1, label: this.$t('等于') }, 
                { value: 2, label: this.$t('大于') }, 
                { value: 3, label: this.$t('大于等于') }, 
                { value: 4, label: this.$t('小于') },
                { value: 5, label: this.$t('小于等于') },
                { value: 6, label: this.$t('包含') }, 
                { value: 7, label: this.$t('包含于') }, 
                { value: 8, label: this.$t('不等于') },
                { value: 9, label: this.$t('不包含') },
                { value: 10, label: this.$t('不包含于') }],
            vTypeOptions:[
                { value: 1, label: this.$t('文本(String)') }, 
                { value: 10, label: this.$t('文本(Int)') }, 
                { value: 2, label: this.$t('Login者ID') }, 
                { value: 3, label: this.$t('Login者账号') },
                { value: 4, label: this.$t('Login者公司') }, 
                { value: 41, label: this.$t('Login者公司及下属公司') }, 
                { value: 5, label: this.$t('Login者部门') }, 
                { value: 51, label: this.$t('Login者部门及下属部门') },
                { value: 6, label: this.$t('Login者岗位') }, 
                { value: 7, label: this.$t('Login者角色') }
            ],

            conditions:[],
            formulas:[],
            numIndex:['A','B','C','D','E','F','G','H','I','J','K','L','M','N',
            'O','P','Q','R','S','T','U','V','W','X','Y','Z'],

            appList:[]
        }
    },
    async created () {
        this.lr_loadRoles()
        const appList = await this.$awaitWraper(apiApp.getList())
        if(appList){
            this.appList = appList.filter(t=>t.f_IsSystem == 2)
        }
    },
    asyncComputed:{
      columns:{
        async get(){
            if(this.formData.f_Code){
                const module = this.modules.find(t=>t.f_ModuleId == this.formData.f_Code)
                let res
                let formScheme

                if(module){
                    res = await this.$awaitWraper(api.getScheme(module.f_UrlAddress))
                    formScheme = JSON.parse(res.formScheme.f_Scheme)
                }
                else {
                    const appModule = this.appList.find(t=>t.f_Id == this.formData.f_Code)
                    res = await this.$awaitWraper(apiScheme.getHistory(appModule.f_FormVerison))
                    formScheme = JSON.parse(res.f_Scheme)
                }

                

                

                let columns = []
                if(formScheme){
                    //console.log(formScheme,'formScheme')

                    formScheme.formInfo.tabList.forEach(tab=>{
                        columns.push(...tab.components.filter(t=>!['gridtable','divider','password'].includes(t.type)))
                    })

                    if(formScheme.formType == 1){
                        columns = columns.map(t=>{ return {...t,value:`${t.field}`} })
                        const rdb = formScheme.rdb || []
                        rdb.forEach(item=>{
                            columns.push({
                                type:'glbd',
                                value:`${item.id}_${item.cfield}`,
                                label:item.fname,

                                table:item.name,
                                cfield:item.cfield,
                                field:item.field,
                                relationField:`${item.relationField}`
                            })
                        })
                    }
                    else{
                        columns = columns.map(t=>{ return {...t,value:`${t.field}${formScheme.db.findIndex(t2=>t2.name == t.table)}`} })
                        const rdb = formScheme.rdb || []
                        rdb.forEach(item=>{
                            columns.push({
                                type:'glbd',
                                value:`${item.id}_${item.cfield}`,
                                label:item.fname,

                                table:item.name,
                                cfield:item.cfield,
                                field:item.field,
                                relationField:`${item.relationField}${formScheme.db.findIndex(t=>t.name == item.relationName)}`
                            })
                        })
                    }

                    
                    
                }

                return columns
            }
            else{
                return []
            }
        }
      }
    },
    computed:{
        ...mapGetters(["modules"]),
        myModules(){
            const res = []
            const pcList = this.modules.filter(t=>t.f_EnabledMark == 1 && t.f_Target == 'custmerForm')

            if(pcList.length >0){
                res.push({
                    label:this.$t('pc端功能'),
                    value:'1',
                    disabled: true,
                    children:pcList.map(t=>({...t,value:t.f_ModuleId,label:t.f_FullName}))
                })
            }

            if(this.appList && this.appList.length >0){
                res.push({
                    label:this.$t('移动端功能'),
                    value:'2',
                    disabled: true,
                    children:this.appList.map(t=>({...t,value:t.f_Id,label:t.f_Name}))
                })
            }



            

           
            return res

            /*if(this.loginInfo.f_SecurityLevel == 1){
                
            }*/
            /*return this.modules.filter(item =>{
                if(item.f_EnabledMark == 1 && item.f_Target == 'custmerForm'){
                    const moduleAuthIds = this.loginInfo.moduleAuthIds || []
                    if(moduleAuthIds.indexOf(item.f_ModuleId) > -1){
                        return true
                    }
                    else{
                        return false
                    }
                }
                else{
                    return false
                }
            })*/
        },
        groupOptions(){
            const res = []
            this.formulas.forEach((item,index)=>{
                res.push({value:this.numIndex[index],label:this.numIndex[index]})
            })
            return res
        }
    },
    methods:{
        resetForm(){
            this.formData.f_Id = ''
            this.conditions = []
            this.$refs.form && this.$refs.form.resetFields()
        },
        // 校验表单
        async validateForm(){
            let valid = await this.$formValidateWraper(this.$refs.form)
            for(let i = 0,len = this.conditions.length;i<len;i++){
                const item =  this.conditions[i]
                if(this.$validatenull(item.f_FieldId)){
                    this.$message({
                        type: 'error',
                        message: this.$t('请填写过滤条件字段!')
                    })
                    valid = false
                    break
                }
                if(this.$validatenull(item.f_Symbol)){
                    this.$message({
                        type: 'error',
                        message: this.$t('please select过滤条件比较符!')
                    })
                    valid = false
                    break
                }
                if(this.$validatenull(item.f_FiledValueType)){
                    this.$message({
                        type: 'error',
                        message: this.$t('please select过滤条件字段值类型!')
                    })
                    valid = false
                    break
                }
                if(this.$validatenull(item.f_FiledValue)){
                    this.$message({
                        type: 'error',
                        message: this.$t('请填写过滤条件字段值!')
                    })
                    valid = false
                    break
                }
            }

            return valid
        },
        setForm(data){
            const formData = data
            const formula = JSON.parse(formData.f_Formula)
            
            formData.f_Formula = formula.formula
            this.conditions = formula.conditions || []
            this.formulas = formula.formulas || []
            this.formData = formData
        },
        getForm(){
            const postData = this.$deepClone(this.formData)
            let formula = {
                formula: postData.f_Formula,
                conditions: this.$deepClone(this.conditions),
                formulas:this.$deepClone(this.formulas)
            }
            postData.f_Formula = JSON.stringify(formula)
            return postData
        },
        handleAddConditions(){
            this.conditions.push({f_FieldId:'',f_Symbol:1,f_FiledValueType:1,f_FiledValue:'',group:''});
        },
        handleRemoveConditions(index){
            this.conditions.splice(index,1);
        },
        handleChangeVType(item){
            if(item.f_FiledValueType == 1 || item.f_FiledValueType == 10){
                item.f_FiledValue = '';
            }
            else{
                item.f_FiledValue = this.vTypeOptions.find(t=>t.value == item.f_FiledValueType ).label;
            }
        },

        handleModuleChange(){
            this.conditions = []
            this.formulas = []
        },

        handleChangeField(item){
            if(item){
                const condition = this.conditions.find(t=>t.f_FieldId == item.value)
                if(item.type == 'glbd'){
                    condition.type = 'glbd'
                    condition.table = item.table
                    condition.cfield = item.cfield
                    condition.field = item.field
                    condition.relationField = item.relationField
                }
                else{
                    condition.type = ''
                    condition.table = ''
                    condition.cfield = ''
                    condition.field = ''
                    condition.relationField = ''
                }
            }
        },


        handleAddFormulas(){
            this.formulas.push({value:''})
        },
        handleRemoveFormulas(index){
            this.formulas.splice(index,1)
        },
        handleChangeGroup(item){
            if(item.type != 'glbd'){
                this.$message({
                    type: 'error',
                    message: this.$t('需要表单关联字段!')
                })
                item.group = ''
            }
            else{
                const conditions = this.conditions.filter(t=>t.group == item.group && item.f_FieldId != t.f_FieldId)
                const conditions2 = conditions.filter(t=>t.field == item.field && t.relationField == item.relationField && t.table == item.table)

                if(conditions.length > 0 && conditions2.length == 0){
                    this.$message({
                        type: 'error',
                        message: this.$t('需要关联同表同字段!')
                    })
                    item.group = ''
                }
            }
            //console.log(conditions,'condition')
            //console.log(item,'xxxx')
        }
    }
}
</script>